/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor. 
 */

package br.com.jr2tecnologia;

import br.com.jr2tecnologia.mail.Mailbox;
import br.com.jr2tecnologia.model.CarrierPersistenceLocal;
import br.com.jr2tecnologia.model.ClientPhonePersistenceLocal;
import br.com.jr2tecnologia.model.LoginPersistenceLocal;
import br.com.jr2tecnologia.model.SmsSendPersistenceLocal;
import br.com.jr2tecnologia.model.entity.ClientPhone;
import br.com.jr2tecnologia.model.entity.Login;
import br.com.jr2tecnologia.model.entity.SmsSend;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;

/**
 *
 * @author ronildo junior
 */

@Stateless
public class MessageSender implements MessageSenderLocal{

    private static final Logger logger = LoggerFactory.getLogger();

    @Resource(mappedName="jms/QueueListenerNowSMSFactory")
    private  ConnectionFactory connectionFactory;
    @Resource(mappedName="jms/QueueListenerNowSMS")
    private  Queue queue; 

    @EJB
    private SmsSendPersistenceLocal smsSendPersistence;
    @EJB
    private ClientPhonePersistenceLocal clientPhonePersistence;
    @EJB
    private LoginPersistenceLocal loginPersistenceLocal;
    @EJB
    private CarrierPersistenceLocal carrierPersistence;

    private void callQueueListenerNowSMS(SmsSend smsSend) throws JMSException{
        Connection connection = connectionFactory.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer messageProducer = session.createProducer(queue);
        ObjectMessage message = session.createObjectMessage();

        message.setObject(smsSend);
        messageProducer.send(message);
        messageProducer.close();
        connection.close();
    }

    private void putSMSToQueue(SmsSend smsSend){
        try{
            callQueueListenerNowSMS(smsSend);
        }catch(Exception ex){
            logger.log(Level.SEVERE,"Não foi possivel enviar esse sms pra fila",ex);
        }
    }

    public void reprocess(SmsSend smsSend){
        if(smsSend.getStatus().equals("PROCESSED")){
            logger.info("save a new sms and reprocess sms with status QUEUED");
            smsSend.setPkSmsSend(null);
            smsSend.setDatetimeSent(null);
            smsSend.setModem(null);
            smsSend.setDatetimeRegistered(new Date());
            smsSend.setStatus("QUEUED");
            smsSend.setDelivered(false);
            smsSendPersistence.persist(smsSend);
            putSMSToQueue(smsSend);
        }else{
            logger.info("reprocess sms " +smsSend.getPkSmsSend() +" with status " + smsSend.getStatus()) ;
            putSMSToQueue(smsSend);
        }
    }

    public void persist(SmsSend smsSend){
        logger.info("persist a new sms to send");
        smsSend.setStatus("QUEUED");
        smsSend.setDelivered(false);
        smsSend.setDatetimeRegistered(new Date());
        smsSendPersistence.persist(smsSend);
        putSMSToQueue(smsSend);
    }

    public void persist(SmsSend smsSend, String phone){
        logger.info("persist a new sms to send");
        ClientPhone clientPhone = clientPhonePersistence.findByPhone(smsSend.getLogin().getCompany(), phone);
        if(clientPhone == null){
            clientPhone = new ClientPhone();
            clientPhone.setName("unknown");
            clientPhone.setPhone(phone);
            clientPhone.setCompany(smsSend.getLogin().getCompany());
            clientPhone.setLogin(smsSend.getLogin());
            clientPhonePersistence.persist(clientPhone);
        }
        smsSend.setClientPhone(clientPhone);

        smsSend.setStatus("QUEUED");
        smsSend.setDelivered(false);
        smsSend.setDatetimeRegistered(new Date());
        smsSendPersistence.persist(smsSend);
        putSMSToQueue(smsSend);
    }

    public void persist(String from, String to, String message){
        Login login = loginPersistenceLocal.findLoginByEmail(from);
        if(login!= null){
            SmsSend smsSend = new SmsSend();
            smsSend.setLogin(login);
            smsSend.setStatus("QUEUED");
            smsSend.setDelivered(false);
            smsSend.setDatetimeRegistered(new Date());
            smsSend.setMessage(message);
            smsSend.setCarrier(carrierPersistence.getDefaultCarrier());

            ClientPhone clientPhone = clientPhonePersistence.findByPhone(login.getCompany(), to);
            if(clientPhone != null){
                smsSend.setClientPhone(clientPhone);
                persist(smsSend);
            }else
                persist(smsSend, to);
        }else{
            Mailbox.post(new String[]{from}, "PERMISSÃO NEGADA AO SMSMAIL", "Desculpas mas a sua caixa postal não esta cadastrada em nosso sistema", "contato@smsmail.com.br");
        }
    }
}
